package sys

import (
	"ginweb-admin/commons/base/api"
	"ginweb-admin/commons/response"
	"ginweb-admin/model/context"
	"ginweb-admin/model/entity/sys"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

type SysUserRoleApi struct {
	api.BaseApi
}

// 用户授权角色
func (api *SysUserRoleApi) SaveSysUserRole(c *gin.Context) {

	// 准备用户授权的上下文
	sysUserRoleContext := context.SysUserRoleContext{}
	// 绑定参数
	err := c.ShouldBindJSON(&sysUserRoleContext)
	if err != nil {
		response.FailWithError(err, c)
		return
	}

	// 对授权的角色进行分割
	roleIdsString := strings.Split(sysUserRoleContext.RoleIds, ",")
	// 准备切片类型的用户角色中间表
	var sysUserRoles []*sys.SysUserRole
	// 把每个分割的角色存到中间表中
	for _, roleId := range roleIdsString {
		// 把字符串转换成数字
		parseUint, _ := strconv.ParseUint(roleId, 10, 64)
		// 准备单个的数据载体
		var sysUserRole sys.SysUserRole
		sysUserRole.UserId = sysUserRoleContext.UserId
		sysUserRole.RoleId = uint(parseUint)
		// 把每个角色的信息存到切片容器中
		sysUserRoles = append(sysUserRoles, &sysUserRole)
	}

	// 调用授权的方法
	err = sysUserRoleService.SaveSysUserRole(sysUserRoleContext.UserId, sysUserRoles)
	if err != nil {
		response.FailWithMessage("用户授权失败！", c)
		return
	}
	response.OkMessage("用户授权成功！", c)
}

// 查询用户授权的角色
func (api *SysUserRoleApi) FindUserRole(c *gin.Context) {
	role, err := sysUserRoleService.FindUserRole(api.GetLoginUserId(c))
	if err != nil {
		response.FailWithMessage("找不到用户授权的角色！", c)
		return
	}
	response.Ok(role, c)
}
